/**
 * 
 */
package net.svenbuschbeck.gwt.ao.client;

import net.svenbuschbeck.gwt.ao.client.events.HasValueChangedHandlers;
import net.svenbuschbeck.gwt.ao.client.events.ValueChangedEvent;
import net.svenbuschbeck.gwt.ao.client.events.ValueChangedHandler;

import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;

/**
 * 
 * 
 * @author Sven Buschbeck
 * @param <Type>
 * 
 */
abstract class ChangedHandler<Type> implements HasValueChangedHandlers<Type> {

	protected Type value;
	private HandlerManager manager = new HandlerManager(null);

	public HandlerRegistration addValueChangedHandler(ValueChangedHandler<Type> valueChangedHandler) {
		return addValueChangedHandler(valueChangedHandler, false);
	}

	@Override public HandlerRegistration addValueChangedHandler(ValueChangedHandler<Type> valueChangedHandler,
		boolean triggerOnceRightAway) {
		HandlerRegistration handlerRegistration = manager.addHandler(ValueChangedEvent.getType(), valueChangedHandler);
		if (triggerOnceRightAway) {
			ValueChangedEvent.fire(this, get(), get());
		}
		return handlerRegistration;
	}

	@Override public void fireEvent(GwtEvent<?> event) {
		manager.fireEvent(event);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override public String toString() {
		return getClass().getName() + "()";
	}

	public String toString(String attributes) {
		return getClass().getName() + "(" + attributes + ")";
	}

	public abstract Type get();
}
